package com.chudian.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.chudian.entity.OrderInfo;
import com.chudian.entity.RefundInfo;
import com.chudian.enums.OrderStatus;
import com.chudian.enums.PayType;
import com.chudian.enums.wxpay.AliTradeState;
import com.chudian.service.AlipayService;
import com.chudian.service.OrderInfoService;
import com.chudian.service.PaymentInfoService;
import com.chudian.service.RefundInfoService;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.Response;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : ZhangCheng
 * @date Date : 2022年11月05日
 */
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private Environment config;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RefundInfoService refundInfoService;

    //定义锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    @Transactional(rollbackForClassName = "Exception.class")
    public String tradeCreate(Long productId) throws AlipayApiException {

        try {
            //根据productId创建订单
            log.info("生成订单");
            OrderInfo orderInfo = orderInfoService.createOrderInfoByProductId(productId, PayType.ALIPAY.getType());

            //调用支付宝接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();//alipay.trade.page.pay接口的请求对象
            //配置需要的公共请求参数
            //支付完成后，支付宝向谷粒学院发起异步通知的地址
            request.setNotifyUrl(config.getProperty("alipay.notify-url"));
            //支付完成后，我们想让页面跳转回谷粒学院的页面，配置returnUrl
            request.setReturnUrl(config.getProperty("alipay.return-url"));

            //组装调用当前接口的必填参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderInfo.getOrderNo());
            //由于支付宝系统的账单金额以元为单位，所以需要进行转换
            BigDecimal total = new BigDecimal(orderInfo.getTotalFee()).divide(new BigDecimal(100));
            bizContent.put("total_amount", total);
            bizContent.put("subject", orderInfo.getTitle());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

            request.setBizContent(bizContent.toString());

            //执行请求，调用支付宝接口
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            String responseBody = response.getBody();//响应体
            String code = response.getCode();//响应码
            if(response.isSuccess()){
                log.info("调用成功,返回结果 ===> {}", responseBody);
                return responseBody;
            } else {
                log.info("调用失败,返回响应码 ===> " + code + ",返回描述：" + response.getMsg());
                throw new RuntimeException("创建支付交易失败！");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("创建支付交易失败！");
        }
    }

    /**
     * 处理订单
     * @param params
     */
    @Override
    public void processOrder(Map<String, String> params) {

        log.info("支付宝支付中根据通知处理订单");

        //获取订单号
        String orderNo = params.get("out_trade_no");

        /*
        在对业务数据进行状态检查和处理之前，
        要采用数据锁进行并发控制，
        以避免函数重入造成的数据混乱
        */
        //尝试获取锁：
        //成功获取则立即返回true，获取失败则立即返回false。不必一直等待锁的释放
        if (lock.tryLock()) {
            try {
                //处理重复通知
                //接口调用的幂等性：无论该接口被调用多少次，下面的操作仅执行一次
                String orderState = orderInfoService.getOrderState(orderNo);
                if (!OrderStatus.NOTPAY.getType().equals(orderState)) {
                    return;
                }

                //更新订单状态
                orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.SUCCESS.getType());

                //记录支付日志
                paymentInfoService.createPaymentInfoForAlipay(params);
            } finally {
                //要主动的释放锁
                lock.unlock();
            }
        }
    }

    /**
     * 用户取消订单
     * @param orderNo
     */
    @Override
    public void cancleOrder(String orderNo) {

        log.info("执行取消订单的业务方法 ===> {}",orderNo);

        //调用支付宝提供的统一收单交易关闭接口
        this.closeOrder(orderNo);

        //更新用户订单状态
        orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.CANCEL.getType());
    }

    /**
     * 查询订单
     * @param orderNo
     * @return 返回订单查询结果，如果返回null则表示支付宝端尚未创建订单
     */
    @Override
    public String queryOrder(String orderNo) {

        try {
            log.info("查单接口调用===>{}",orderNo);

            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("调用成功,返回结果 ===> {}", response.getBody());
                return response.getBody();
            } else {
                log.info("调用失败,返回响应码 ===> " + response.getCode() + ",返回描述：" + response.getMsg());
                //throw new RuntimeException("支付宝的查单接口调用失败！");
                return null;//订单不存在
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("支付宝的查单接口调用失败！");
        }

    }

    /**
     * 根据订单号调用支付宝查单接口，核实订单状态
     * 如果订单未创建，则直接更新商户端订单状态
     * 如果订单未支付，则调用关单接口关闭订单，并更新商户端订单状态
     * 如果订单已支付，则更新商户端订单状态，并记录支付日志
     * @param orderNo
     */
    @Override
    public void checkOrderStatus(String orderNo) {
        log.warn("根据订单号核实订单状态===>{}",orderNo);

        String result = this.queryOrder(orderNo);

        //订单未创建
        if(result == null){
            log.warn("核实订单状态未创建 ===> {}",orderNo);
            //更新本地订单状态
            orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.CLOSED.getType());
        }

        //解析查单响应结果
        Gson gson = new Gson();
        HashMap<String, LinkedTreeMap> resultMap = gson.fromJson(result, HashMap.class);
        LinkedTreeMap alipayTradeQueryResponse = resultMap.get("alipay_trade_query_response");

        //获取支付宝端的订单状态
        String tradeStatus = (String) alipayTradeQueryResponse.get("trade_status");

        //订单未支付
        if(AliTradeState.NOTPAY.getType().equals(tradeStatus)){
            log.warn("核实订单状态未支付 ===> {}",orderNo);
            ///如果订单未支付，则调用关单接口关闭订单
            this.closeOrder(orderNo);
            //并更新商户端订单状态
            orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.CLOSED.getType());
        }

        //订单已支付
        if(AliTradeState.SUCCESS.getType().equals(tradeStatus)){
            log.warn("核实订单状态已支付 ===> {}",orderNo);

            //如果订单已支付，则更新商户端订单状态
            orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.SUCCESS.getType());

            //并记录支付日志
            paymentInfoService.createPaymentInfoForAlipay(alipayTradeQueryResponse);
        }

    }

    /**
     * 退款
     * @param orderNo
     * @param reason
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void round(String orderNo, String reason) {

        try {
            log.info("调用退款API ===> {}",orderNo);

            //创建退款单
            RefundInfo refundInfo = refundInfoService.createRefundByOrderNoForAlipay(orderNo, reason);

            //调用统一收单交易退款接口
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

            //组装当前业务方法的请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            //接口要求参数以“元”为单位，但是退款单以“分”为单位，所以需要转换
            //BigDecimal refundAmount = new BigDecimal(2).divide(new BigDecimal(100));
            BigDecimal refundAmount = new BigDecimal(refundInfo.getRefund()).divide(new BigDecimal(100));
            bizContent.put("refund_amount", refundAmount); //退款金额：不能大于支付金额
            bizContent.put("refund_reason", reason); //退款原因

            request.setBizContent(bizContent.toString());

            //执行请求，调用支付宝接口
            AlipayTradeRefundResponse response = alipayClient.execute(request);

            if(response.isSuccess()){
                log.info("调用成功,返回结果 ===> {}", response.getBody());

                //更新订单状态
                orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.REFUND_SUCCESS.getType());

                //更新退款单
                refundInfoService.updateRefundForAlipay(
                        refundInfo.getRefundNo(),
                        response.getBody(),
                        AliTradeState.REFUND_SUCCESS.getType()  //退款成功
                        );

            } else {
                log.info("调用失败,返回响应码 ===> " + response.getCode() + ",返回描述：" + response.getMsg());

                //更新订单状态
                orderInfoService.updateOrderStatusByOrderno(orderNo, OrderStatus.REFUND_ABNORMAL.getType());

                //更新退款单
                refundInfoService.updateRefundForAlipay(
                        refundInfo.getRefundNo(),
                        response.getBody(),
                        AliTradeState.REFUND_ERROR.getType()); //退款失败

            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("创建退款申请失败！");
        }
    }

    /**
     * 查询退款
     * @param orderNo
     * @return
     */
    @Override
    public String queryRefund(String orderNo) {

        try {
            log.info("查询退款接口调用 ===> {}", orderNo);

            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            bizContent.put("out_request_no", orderNo);
            request.setBizContent(bizContent.toString());

            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("调用成功,返回结果 ===> {}", response.getBody());
                return response.getBody();
            } else {
                log.info("调用失败,返回响应码 ===> " + response.getCode() + ",返回描述：" + response.getMsg());
                //throw new RuntimeException("支付宝的查单接口调用失败！");
                return null;//订单不存在
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("查单接口调用失败！");
        }
    }

    /**
     * 调用支付宝的关单接口关闭订单
     * @param orderNo 订单号
     */
    private void closeOrder(String orderNo) {

        try {
            log.info("支付宝的关单接口调用，订单号 ===> {}",orderNo);

            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("调用成功,返回结果 ===> {}", response.getBody());
            } else {
                log.info("调用失败,返回响应码 ===> " + response.getCode() + ",返回描述：" + response.getMsg());
                //throw new RuntimeException("支付宝的关单接口调用失败！");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("支付宝的关单接口调用失败！");
        }
    }
}
